import React, { useEffect, useState } from "react";
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  Spinner,
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  Chip,
  Tooltip,
  Divider
} from "@nextui-org/react";
import { getNoteShares, cancelShare } from "@/app/service/shareService.tsx";
import dayjs from "dayjs";
import { MdOutlineOpenInNew } from "react-icons/md";
import { IoCopyOutline } from "react-icons/io5";
import { HiOutlineTrash } from "react-icons/hi";
import { BiPlus } from "react-icons/bi";
import CreateShareModal from "./CreateShareModal";
import ToastUtil from "@/app/utils/toastUtil";
import copy from "copy-to-clipboard";

interface NoteShareModalProps {
  noteId: number | null;
  isOpen: boolean;
  onClose: () => void;
  onShareCreated?: () => void;
  onShareCanceled?: () => void;
}

// 客户端渲染钩子
function useClientOnly() {
  const [isMounted, setIsMounted] = useState(false);
  
  useEffect(() => {
    setIsMounted(true);
  }, []);
  
  return isMounted;
}

export default function NoteShareModal({ 
  noteId, 
  isOpen, 
  onClose, 
  onShareCreated,
  onShareCanceled
}: NoteShareModalProps) {
  const isMounted = useClientOnly();
  const [loading, setLoading] = useState(false);
  const [shares, setShares] = useState<any[]>([]);
  const [showCreateModal, setShowCreateModal] = useState(false);
  
  console.log("NoteShareModal渲染 - noteId:", noteId, "isOpen:", isOpen);
  
  // 当模态框打开且有笔记ID时，获取笔记的分享
  useEffect(() => {
    console.log("useEffect触发 - noteId:", noteId, "isOpen:", isOpen);
    
    if (isOpen && noteId) {
      console.log("准备获取笔记分享，noteId:", noteId);
      fetchNoteShares();
    }
  }, [isOpen, noteId]);
  
  // 获取笔记分享
  const fetchNoteShares = async () => {
    if (!noteId) {
      console.log("fetchNoteShares - noteId不存在，返回");
      return;
    }
    
    console.log("fetchNoteShares开始执行 - noteId:", noteId);
    setLoading(true);
    try {
      console.log("调用getNoteShares API - noteId:", noteId);
      const response = await getNoteShares(noteId, 1, 10);
      console.log("获取分享数据返回:", response);
      
      // 检查完整的响应结构
      if (response) {
        // API响应格式：{ code, status, message, data: { records, total, ... } }
        if (response.code === 200 && response.data && response.data.records) {
          console.log("设置分享数据 - 记录数:", response.data.records.length);
          setShares(response.data.records);
        } else if (response.records) {
          // 向后兼容，以防response直接就是data部分
          console.log("向后兼容 - 直接使用records");
          setShares(response.records);
        } else {
          console.log("没有找到records字段或格式不正确 - 完整返回:", JSON.stringify(response));
          setShares([]);
        }
      } else {
        console.log("响应为空");
        setShares([]);
      }
    } catch (error) {
      console.error("获取笔记分享失败:", error);
      setShares([]);
    } finally {
      setLoading(false);
    }
  };
  
  // 处理取消分享
  const handleCancelShare = async (shareId: number) => {
    try {
      await cancelShare(shareId);
      await fetchNoteShares();
      
      if (onShareCanceled) {
        onShareCanceled();
      }
    } catch (error) {
      console.error("Failed to cancel share:", error);
    }
  };
  
  // 复制分享链接
  const copyShareLink = (share: any) => {
    // 优先使用API返回的shareLink，如果没有则自己构建
    const link = share.shareLink || `${window.location.origin}/view/${share.token}`;
    copy(link);
    ToastUtil("分享链接已复制到剪贴板", "🎉", "success");
  };
  
  // 打开分享链接
  const openShareLink = (share: any) => {
    // 优先使用API返回的shareLink，如果没有则自己构建
    const link = share.shareLink || `${window.location.origin}/view/${share.token}`;
    window.open(link, "_blank");
  };
  
  // 处理创建分享成功
  const handleShareCreated = () => {
    setShowCreateModal(false);
    fetchNoteShares();
       
    // 创建分享成功后自动关闭主模态框
    onClose();
    
    if (onShareCreated) {
      onShareCreated();
    }
  };
  
  // 格式化日期
  const formatDate = (dateString: string) => {
    if (!dateString) return "未设置";
    return dayjs(dateString).format("YYYY-MM-DD HH:mm");
  };
  
  // 判断是否过期
  const isExpired = (dateString: string) => {
    if (!dateString) return false;
    return dayjs(dateString).isBefore(dayjs());
  };

  // 只在客户端渲染此组件
  if (!isMounted) {
    return null;
  }

  return (
    <>
      <Modal isOpen={isOpen} onClose={onClose} size="md">
        <ModalContent>
          <ModalHeader className="flex flex-col gap-1">笔记分享</ModalHeader>
          <ModalBody>
            {loading ? (
              <div className="flex justify-center py-8">
                <Spinner color="primary" label="加载中..." />
              </div>
            ) : shares.length === 0 ? (
              <div className="flex flex-col items-center py-8 gap-4">
                <p className="text-default-500">该笔记暂无分享 (ID: {noteId})</p>
                <p className="text-xs text-gray-400">如果有分享记录但未显示，请检查控制台日志</p>
                <Button 
                  color="primary" 
                  startContent={<BiPlus />}
                  onPress={() => setShowCreateModal(true)}
                >
                  创建分享
                </Button>
              </div>
            ) : (
              <>
                <Table aria-label="笔记分享列表">
                  <TableHeader>
                    <TableColumn>权限</TableColumn>
                    <TableColumn>过期时间</TableColumn>
                    <TableColumn>操作</TableColumn>
                  </TableHeader>
                  <TableBody>
                    {shares.map((share) => (
                      <TableRow key={share.id}>
                        <TableCell>
                          <Chip
                            size="sm"
                            variant="flat"
                            color={share.permission === "WRITE" ? "warning" : "success"}
                          >
                            {share.permission === "WRITE" ? "可编辑" : "只读"}
                          </Chip>
                        </TableCell>
                        <TableCell>
                          <Chip
                            size="sm"
                            variant="dot"
                            color={isExpired(share.expiredAt) ? "danger" : "success"}
                          >
                            {formatDate(share.expiredAt)}
                          </Chip>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Tooltip content="复制链接">
                              <Button 
                                isIconOnly 
                                size="sm" 
                                variant="light" 
                                onPress={() => copyShareLink(share)}
                              >
                                <IoCopyOutline size={18} />
                              </Button>
                            </Tooltip>
                            <Tooltip content="打开链接">
                              <Button 
                                isIconOnly 
                                size="sm" 
                                variant="light" 
                                onPress={() => openShareLink(share)}
                              >
                                <MdOutlineOpenInNew size={18} />
                              </Button>
                            </Tooltip>
                            <Tooltip content="取消分享" color="danger">
                              <Button 
                                isIconOnly 
                                size="sm" 
                                variant="light" 
                                color="danger"
                                onPress={() => handleCancelShare(share.id)}
                              >
                                <HiOutlineTrash size={18} />
                              </Button>
                            </Tooltip>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
                
                <Divider className="my-2" />
                
                <div className="flex justify-center">
                  <Button 
                    color="primary" 
                    startContent={<BiPlus />}
                    onPress={() => setShowCreateModal(true)}
                  >
                    创建新分享
                  </Button>
                </div>
              </>
            )}
          </ModalBody>
          <ModalFooter>
            <Button color="default" variant="light" onPress={onClose}>
              关闭
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
      
      {noteId && (
        <CreateShareModal
          noteId={noteId}
          isOpen={showCreateModal}
          onClose={() => setShowCreateModal(false)}
          onSuccess={handleShareCreated}
        />
      )}
    </>
  );
} 